<?php
namespace app\index\service;
/**
* Class: MerchantService 
* 商户服务类
* Author: Jason ZHENG <mingjun.zheng@zengduokeji.com>
* Date : 2018-09-23
**/
use app\index\controller\ReturnData;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use app\index\common;
use app\index\service\BaseService;
use think\Config;
use app\common\lib\YopClient3;
use app\common\lib\YopRequest;
use app\common\controller\Helptype;

class MerchantService
{
    public static function branch($data='')
    {
        $config  = Config::get('yeepay');
        $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
        
        $request->addParam("headBankCode", $data['headBankCode']);//开户银行总行编码
        $request->addParam("provinceCode", $data['provinceCode']);//开户省
        $request->addParam("cityCode", $data['cityCode']);//开户市

        $response = YopClient3::post("/rest/v1.0/sys/merchant/bankbranchinfo", $request);
        //取得返回结果
        $result = Helptype::object_array($response);
        if($result['state'] == 'SUCCESS')
            return $result['result'];
        else{
            var_dump($result);exit();
        }       
    }
    public static function modify_billing_card($data='')
    {
         $config  = Config::get('yeepay');
        $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
        $request->addParam("parentMerchantNo", $data['parentMerchantNo']);
        $request->addParam("merchantNo", $data['merchantNo']);
        
        $request->addParam("merAuthorizeNum", $data['merAuthorizeNum']);//验证码
        $request->addParam("bankcardNo", $data['bankcardNo']);//银行卡号
        $request->addParam("headBankName", $data['headBankName']);//开户总行编码
        $request->addParam("bankName",$data['bankName']);//开户银行分行银行编码
        $request->addParam("bankProvince", $data['bankProvince']);//开户省
        $request->addParam("bankCity", $data['bankCity']);//
        $request->addParam("requestNo", $data['requestNo']);//入网请求号
        $request->addParam("SETTLE", 'SETTLE');//结算卡

        $response = YopClient3::post("/rest/v1.0/merchantService/mer-settle/mer-settle-info-update-for-o2o", $request);
        //取得返回结果
        $result = Helptype::object_array($response);
        if($result['state'] == 'SUCCESS')
            return $result['result'];
        else{
            var_dump($result);exit();
        }       
    }
    /**
     * [phone_code 向易宝请求验证码]
     * @author 刘家腾
     * @DateTime 2018-09-30T17:38:10+0800
     * @param    [type]                   $data [description]
     * @return   [type]                         [description]
     */
    public static function phone_code($data)
    {
        $config  = Config::get('yeepay');
        $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
        $request->addParam("parentMerchantNo", $data['parentMerchantNo']);
        $request->addParam("merchantNo", $data['merchantNo']);
        $request->addParam("sourceType", $data['sourceType']);
        $request->addParam("phone", $data['phone']);

        $response = YopClient3::post("/rest/v1.0/merchantService/mer-out-invoke/send-mer-sms-notify", $request);
        //取得返回结果
        $result = Helptype::object_array($response);
        if($result['state'] == 'SUCCESS')
            return $result['result'];
        else{
            var_dump($result);exit();
        }       
    }

	// 向易宝发送提现请求
	public static function withdrawMoney($data,$money)
	{
		$money = sprintf('%.2f',$money);
		$config  = Config::get('yeepay');
	    $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
	    $request->addParam("groupNumber", $data['parentMerchantNo']);
	    $request->addParam("customerNumber", $data['merchantNo']);
	    $request->addParam("amount", (string)$money);
	    $request->addParam("orderId", $data['orderId']);
	    $request->addParam("cashType", $data['cashType']);
	    $request->addParam("feeType", $data['feeType']); 

	    $response = YopClient3::post("/rest/v1.0/balance/cash", $request);
	    //取得返回结果
	    $result = Helptype::object_array($response);

        Helptype::yibaoLog(7,'withdraw',json_encode($request),json_encode($result));

	    if($result['state'] == 'SUCCESS')
	    	return $result['result'];
	    else{
	    	var_dump($result);exit();
	    }	    
 	}

    
 	/**
     * @param $user_id
     * @return int|mixed
     * 获取当前商户账户余额
     */
    public static function get_balance($user_id,$state)
    {

        try{

            //进账记录
            $moneyIn = Db::table('merchant_currency')
                ->where(['user_id'=>$user_id,'type'=>1])
                ->field('money,fee')
                ->select();
            //出账记录
            $moneyOut = Db::table('merchant_currency')
                ->where(['user_id'=>$user_id,'type'=>2])
                ->field('money,fee')
                ->select();

            //进账总金额
            $moneyIntTotal = 0;
            foreach ($moneyIn as $key => $mo) {
                $moneyIntTotal = $moneyIntTotal + $mo['money'];
            }

            //出账总金额
            $moneyOutTotal = 0;
            foreach ($moneyOut as $key => $mo) {
                $moneyOutTotal = $moneyOutTotal + $mo['money'];
            }

            //总金额 = 总进账 - 总出账
            $moneyTotal = round(($moneyIntTotal - $moneyOutTotal),2);

            if(empty($moneyIn)){
                return 0;
            }
            // 可提现资金
            $avalableMoney = 0;
            
            $result = self::getWithdrawMondy($user_id);
            if(isset($result['errorCode']) && $result['errorCode']!= null )
            {
                $avalableMoney = '0.00';
            }else{
                $avalableMoney = $result['d1ValidAmount'];
            }
            $moneyLeft = '0.00';
            if($state == 0){
                // 不可提现余额
                $moneyLeft = round(($moneyTotal - $avalableMoney),2);
            }elseif($state == 1){
                // 可提现余额
                $moneyLeft = $avalableMoney;
            }elseif($state == 2){
                // 总余额
                $moneyLeft = $moneyTotal;
            }  
            return $moneyLeft;
        }catch(Exception $e){
            $back['code'] = -1;
            $back['msg'] = $e->getMessage();
            return $back;
        }
	}

    /**
     * @param $user_id
     * @return int|mixed
     * 获取当前商户账户余额
     */
    public static function get_balance_old($user_id,$state)
    {

        try{
            
            //进账记录
            $moneyIn = Db::table('merchant_currency')
                ->where(['user_id'=>$user_id,'state'=>$state,'type'=>1])
                ->field('money,fee')
                ->select();
            //出账记录
            $moneyOut = Db::table('merchant_currency')
                ->where(['user_id'=>$user_id,'type'=>2, 'state' =>$state])
                ->field('money,fee')
                ->select();
            //出账总金额
            $moneyOutTotal = 0;
            foreach ($moneyOut as $key => $mo) {
                $moneyOutTotal = $moneyOutTotal + $mo['money'];
            }

            if(empty($moneyIn)){
                return 0;
            }
            $moneyLeft = 0;
            if(0==$state){
                // 冻结资金（不可提现）
                foreach($moneyIn as $v){
                    $moneyLeft =  $v['money'] +$moneyLeft;
                }
            }else{
                // 可提现资金
                // foreach($moneyIn as $v){
                //     $moneyLeft =  $v['money'] +$moneyLeft;
                // }
                // $moneyLeft = $moneyLeft - $moneyOutTotal;
                $result = self::getWithdrawMondy($user_id);
                if(isset($result['errorCode']) && $result['errorCode']!= null )
                {
                    //return ['code'=>1007,'msg'=>$result['errorMsg'],'data'=> $result]; exit();
                    $moneyLeft = '0.00';
                }else{
                    $moneyLeft = $result['d1ValidAmount'];
                }
                
            }
            return $moneyLeft;
        }catch(Exception $e){
            $back['code'] = -1;
            $back['msg'] = $e->getMessage();
            return $back;
        }
    }

 	//获取可提现余额
 	public static function getWithdrawMondy($user_id)
    {
        $merchant = Db::table('merchant')->where(['user_id'=>$user_id])->find();
        if($merchant == null){
            return ['code'=>1001,'msg'=>'商户不存在','data'=>'']; 
        }
        $config  = Config::get('yeepay');
        $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
        $request->addParam("groupNumber", $merchant['parentMerchantNo']);
        $request->addParam("customerNumber", $merchant['merchantNo']);

        $response = YopClient3::post("/rest/v1.0/balance/account-query", $request);
        //取得返回结果
        $result = Helptype::object_array($response);

        Helptype::yibaoLog(9,'account',json_encode($request),json_encode($result));

        if($result['state'] == 'SUCCESS')
            return $result['result'];
        else{
            return 0;
        }
    }

    // 提现查询
    public static function getWithdrawState($user_id, $order_id )
    {
        $merchant = Db::table('merchant')->where(['user_id'=>$user_id])->find();
        if($merchant == null){
            return ['code'=>1001,'msg'=>'商户不存在','data'=>'']; 
        }
        $config  = Config::get('yeepay');
        $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
        $request->addParam("groupNumber", $merchant['parentMerchantNo']);
        $request->addParam("customerNumber", $merchant['merchantNo']);
        $request->addParam("orderId", $order_id);
        $request->addParam("cashType", 'D1');

        $response = YopClient3::post("/rest/v1.0/balance/query-cash-byorder", $request);
        //取得返回结果
        $result = Helptype::object_array($response); 
        return $result;
    }

    //对账查询
    public static function getYibaoCurrency($path, $merchantNo, $method, $dataType, $date)
    {
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, 'https://yos.yeepay.com/yop-center');
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        $post_data = [
            "merchantNo"    => $merchantNo,
            "method"        => $method,
            "dataType"      => $dataType,
            "date"          => $date,
        ];
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $file_content = curl_exec($curl);

        //存储文件
        file_put_contents($path, $file_content);

        //关闭URL请求
        curl_close($curl);
    }

    public static function delete_data($user_id){
        Db::startTrans();
        try{
            Db::table('merchant') //认证信息基本表
            ->where(['user_id'=>$user_id])
                ->delete();
            Db::table('merchant_resource') //认证信息图片表
            ->where(['user_id'=>$user_id])
                ->delete();
            Db::table('merchant_resource_own')
                ->where(['user_id'=>$user_id])
                ->delete();
            Db::table('merchant_resource_yeepay')//认证信息易宝图片表
            ->where(['user_id'=>$user_id])
                ->delete();
            Db::table('merchant_resource_thumb')
                ->where(['user_id'=>$user_id])
                ->delete();
            Db::commit();
            return ReturnData::ok('数据检测完成','ok');
        }catch(Exception$e){
            Db::rollback();
            return ReturnData::error(-1,$e->getMessage());
        }
    }














}
